import gio
import gtk
import threading
from mmxfer import mediatype
from mmxfer import store
import traceback
import tempfile
import time
import simplemtp
from mutagen.easyid3 import EasyID3
import os

class WorkerThread_Transfer(threading.Thread):
	def __init__(self,lstore):
		threading.Thread.__init__(self)
		self.lstore=lstore
	def run(self):
		mtp=simplemtp.MTP()
		while not self.lstore.quit_event.is_set():
			#try to connect
			try:
				mtp.connect()
			except simplemtp.NoDeviceConnected:
				self.lstore.quit_event.wait(1)
				continue
			try:
				while not self.lstore.quit_event.is_set():
					gtk.gdk.threads_enter()
					task_row=None
					for row in self.lstore:
						if row[store.column("waiting")] \
								and row[store.column("type")]==mediatype.MT_AUDIO_UPLOADABLE:
							task_row=row
							break
					if task_row is None:
						gtk.gdk.threads_leave()
						self.lstore.quit_event.wait(1)
						continue
					task_row[store.column("status")]=mediatype.get_description(mediatype.MT_AUDIO_UPLOADABLE,False)
					task_row[store.column("waiting")]=False
					filename=gio.File(task_row[store.column("uri")]).get_path()
					gtk.gdk.threads_leave()
					result=False
					tags=False
					try:
						track=simplemtp.LIBMTP_Track()
						try:
							audio=EasyID3(filename)
							for key in EasyID3.valid_keys.keys():
								try:
									if key=="tracknumber":
										track.__setattr__(key,int(audio[key][0]))
									else:
										track.__setattr__(key,str(audio[key][0]))
								except: pass
							tags=True
						except:pass
						track.filename=os.path.basename(filename)
						if track.title=="":
							track.title=track.filename
						if track.album=="":
							track.album="UNKNOWN"
						if track.artist=="":
							track.artist="UNKNOWN"
						track.filetype=simplemtp.LIBMTP_Filetype["MP3"]
						mtp.send_track_from_file_detailed(filename,track,self.progress_callback,task_row)
						result=True
					finally:
						gtk.gdk.threads_enter()
						if result:
							if not tags:
								task_row[store.column("status")]="Finished (No Tags!)"
							else:
								task_row[store.column("status")]="Finished"
							task_row[store.column("progress")]=100.0
						else:
							task_row[store.column("type")]=mediatype.MT_UNKNOWN
							task_row[store.column("status")]=mediatype.get_description(mediatype.MT_UNKNOWN,False)
							task_row[store.column("progress")]=0.0
							task_row[store.column("waiting")]=True
						gtk.gdk.threads_leave()
			except:
				traceback.print_exc()
			try:mtp.disconnect()
			except:pass
				

				
	def progress_callback(self,total,sent,row):
		try:
			gtk.gdk.threads_enter()
			row[store.column("progress")]=float(sent)/float(total)*100.0
		finally:
			gtk.gdk.threads_leave()
